--- 用户登录, 通过sql存储, 成功设置cookie
ngx.header["Content-Type"] = "application/json;charset=UTF-8"

ngx.req.read_body()
local args, err = ngx.req.get_post_args()
if not args then
    ngx.say("failed to get post args: ", err)
    return
end

local user_name = args['user_name']
local passwd = args['passwd']
if user_name == nil or passwd == nil then
    ngx.say("failed to login: args error")
    return
end

--- mysql
local db, err = mysql:new()
if not db then
    ngx.say("failed to instantiate mysql: ", err)
    return
end
db:set_timeout(1000)

local ok, err, errcode, sqlstate = db:connect(extrauth_cons.db_options)
if not ok then
    ngx.say("failed to connect: ", err, ": ", errcode, " ", sqlstate)
    return
end
-- ngx.say("connected to mysql.")

-- do sql
user_name = ngx.quote_sql_str(user_name)
-- passwd = ngx.quote_sql_str(passwd)
-- encrypt passwd
local epasswd = ngx.encode_base64(ngx.hmac_sha1(extrauth_cons.salt, passwd))
local sql = string.format(extrauth_cons.sql_select_user, user_name, epasswd)

res, err, errcode, sqlstate = db:query(sql)
--todo test如果表不存在
if not res then
    ngx.say("bad result: ", err, ": ", errcode, ": ", sqlstate, ".")
    return
end

if not res[1] then
    ngx.log(ngx.ERR, "Try to login error: ", user_name, " with pass ", passwd)
    ngx.say("user_name or passwd error")
    return
end

--- put into conn pool
local ok, err = db:set_keepalive(10000, 100)
if not ok then
    ngx.say("failed to set keepalive: ", err)
    return
end


--认证用cookie长这样: 名为 extrauth_{auth_group}_token,
-- 内容为 base64(sha1(salt,basic_text)):basic_text  basic_text为 user_id:admin:groups:timeout_time

local now = os.time()
local expire = now + extrauth_cons.login_timeout --过期时间
local basic_text = res[1]['user_id'] .. extrauth_cons.divider .. res[1]['is_admin'] .. extrauth_cons.divider .. res[1]['groups'] .. extrauth_cons.divider .. expire
local hmac = ngx.encode_base64(ngx.hmac_sha1(extrauth_cons.salt, basic_text))
local token = hmac .. extrauth_cons.divider .. basic_text

ngx.header["Set-Cookie"] = 'extrauth_token=' .. token .. '; path=/; expires=' .. ngx.cookie_time(expire)
ngx.log(ngx.ERR, "user login success ", user_name .. " from " .. ngx.var.remote_addr)

local redirect_cookie = ngx.var['cookie_extrauth_redirect']

if redirect_cookie then 
    local redirect_url = ndk.set_var.set_unescape_uri(redirect_cookie)
    ngx.redirect(redirect_url)
else 
    ngx.say("login success, reentry that page")
end
